package com.htdata.iiot.file.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.htdata.iiot.file.utils.ApiResultDto;
import com.htdata.iiot.file.utils.Config;
import com.htdata.iiot.file.utils.ContentType;
import com.htdata.iiot.file.utils.IteratorFileUtil;

/**
 * Created by SunMy on 2017/7/14.
 */
@RestController
public class FileController {
	private static Logger logger = LoggerFactory.getLogger(FileController.class);

	@RequestMapping(value = "/upload", method = RequestMethod.POST,produces="text/plain;charset=utf-8")
	public String upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "*");

		if (!(request instanceof MultipartHttpServletRequest)) {
			return "error";
		}
		MultipartHttpServletRequest fileRequest = (MultipartHttpServletRequest)request;
		String tenantId = fileRequest.getParameter("tenantId");
		
		MultiValueMap<String,MultipartFile> multiFileMap = fileRequest.getMultiFileMap();
		Collection<List<MultipartFile>> files = multiFileMap.values();
		
		if(tenantId==null||tenantId.isEmpty()){
			tenantId="0";
		}
		int i=0;
		StringBuilder paths = new StringBuilder();
		for(List<MultipartFile> fileList:files){
			
			for(MultipartFile uploadFile:fileList){
				String type = ContentType.getExpandByContentType(uploadFile.getContentType());
				String fileName =  getRandomFileName(type);
				File file = new File(Config.FILE_PATH+Config.SEPARATOR+tenantId+Config.SEPARATOR+fileName);
				if(!file.exists()){
					File parentFile = file.getParentFile();
					if(!parentFile.exists()){
						parentFile.mkdirs();
					}
					file.createNewFile();
				}
				FileOutputStream fileOutputStream = new FileOutputStream(file);
				fileOutputStream.write(uploadFile.getBytes());
				fileOutputStream.flush();
				fileOutputStream.close();
				if(i!=0){
					paths.append(",");
				}
				paths.append(Config.SERVER_ADDRESS+"/"+tenantId+"/"+fileName);
				i++;
			}
		}
		
		//写文件
		
        return paths.toString(); 

	}

	@RequestMapping(value = "/list",method = RequestMethod.GET,produces={"application/json;charset=utf-8"})
	public String getImgList(@RequestParam(defaultValue="0" ,name="tenantId",required=false) int tenantId,  HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "*");

		//遍历该目录下所有文件夹获取文件名称，拼接成url放imgList
		StringBuilder re=new StringBuilder();
		IteratorFileUtil.IteratorDir(new File(Config.FILE_PATH+Config.SEPARATOR+tenantId),re);
		List<String> imageUrls=new ArrayList<String>();
		if(null!=re&&re.length()>0){
			String temp=re.toString();
			String[] split = StringUtils.split(temp,",");
			for (String item:split){
				imageUrls.add(item);
			}
		}

		logger.info("/list 租戶《{}》目录《{}》下的imgUrls:{}",tenantId,Config.FILE_PATH+Config.SEPARATOR+tenantId,imageUrls);

		ApiResultDto result = new ApiResultDto();
		result.setCode(0);
		result.setData(imageUrls);
		result.setDescription(ApiResultDto.SUCCESS);
		return result.toJsonString();

	}
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String testSDK() {
		
		return "upload";
	}
	@RequestMapping(value = "/move", method = RequestMethod.GET,produces={"text/plain;charset=utf-8"})
	public String invoke(@RequestParam String src,@RequestParam String tenantId , HttpServletResponse response) throws IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "*");

		tenantId = (null==tenantId)?"0":tenantId;

		if(src==null){
			return "error request";
		}
		
		//取出文件路径
		src = src.replace(Config.SERVER_ADDRESS, "");
		//移动文件
		moveTotherFolders(Config.FILE_PATH +Config.SEPARATOR+ src, Config.FILE_PATH +Config.SEPARATOR+tenantId+"/"+src);
		//返回新的访问路径
		if(src.startsWith("/")){
			src=src.substring(1);
		}
		String path = Config.SERVER_ADDRESS+"/"+tenantId+"/"+src;
		return path;
	}

	private void moveTotherFolders(String oldFilePath, String newFilePath) {
		try {
			File tmpFile = new File(newFilePath);
			File startFile = new File(oldFilePath);
			if (!tmpFile.getParentFile().exists()) {
				tmpFile.getParentFile().mkdirs();
			}
			
			String property = System.getProperty("os.name");
			
			if(property.indexOf("Windows")>=0){
				
				Runtime.getRuntime().exec("C:/Windows/System32/cmd.exe /k move " + startFile.getPath() + " " + tmpFile.getPath());
			}else{
				Runtime.getRuntime().exec("mv " + oldFilePath + " " + newFilePath);
			}
			

			startFile = new File(oldFilePath);
			tmpFile = new File(newFilePath);// 获取文件夹路径
			if (tmpFile.exists() && !startFile.exists()) {// 判断文件夹是否创建，没有创建则创建新文件夹
				System.out.println("File is moved successful!");
				logger.info("文件移动成功！文件名：《{}》 目标路径：{}", oldFilePath, newFilePath);
			} else {
				System.out.println("File is failed to move!");
				logger.info("文件移动失败！文件名：《{}》 起始路径：{}", oldFilePath, newFilePath);
			}
		} catch (Exception e) {
			logger.info("文件移动异常！文件名：《{}》 起始路径：{}", oldFilePath, newFilePath);

		}
	}

	

	public static String getRandomFileName(String type) {
		Date day = new Date();
		StringBuffer buffer = new StringBuffer();
		Random random = new Random();
		long ms = System.currentTimeMillis() % 86400000;
		buffer.append(Long.toHexString(ms));
		for (int i = 0; i < 10; i++) {
			buffer.append(Integer.toHexString(random.nextInt(15)));
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd/");
		String date = df.format(day);
		return date + buffer.toString() + type;
	}
}
